# coding:utf-8

import time
import threading

import pymongo

from fralog.FraLog import Fralog
from wechat.sendmsg import WeBot
from globalsettings import CUR_MODE
if CUR_MODE == 'dev':
    from globalsettings_dev import *
else:
    from globalsettings_prod import *

log = Fralog().getFileLog()

host = MONGO_HOST
port = MONGO_PORT


def _get_db_client(dbname='survey_database'):
    """
    获取到mongodb的链接
    :return: 
    """
    if MONGO_DB_PWD is None or MONGO_DB_PWD == '':
        client = pymongo.MongoClient(host=MONGO_HOST, port=MONGO_PORT, socketKeepAlive=True)  # 连接数据库
    else:
        client = pymongo.MongoClient(host=MONGO_HOST, port=MONGO_PORT, username=MONGO_DB_USERNAME,
                                     password=MONGO_DB_PWD, socketKeepAlive=True)  # 连接数据库

    db = client[dbname]
    db.responses_collection.create_index([('code', pymongo.ASCENDING), ('response.wxid', pymongo.ASCENDING)])
    db.products_collection.create_index([('wxuser.openid', pymongo.ASCENDING)])
    db.user_collection.create_index([('openid', pymongo.ASCENDING)])
    # db.wxuser.create_index([('openid', pymongo.ASCENDING)])
    return (db, client)


def _get_channel(db, channel):
    """
    获取指定渠道的数据
    :param db: 
    :param channel: 
    :return: 
    """
    log.info('渠道名： %s'%(channel))
    rows = db.responses_collection.find({"response.channel": channel})
    log.info('当前记录条数: %d'%(rows.count()))
    return rows


def _get_channel_distinct(db, channel):
    """
    获取去重后的问卷填写人数

    :param db: 
    :param channel: 
    :return: 
    """
    rows = db.responses_collection.find({"response.channel": channel}).distinct("response.wxid")
    if rows is None:
        return 0
    else:
        return len(rows)

cur_count = {}

cur_count['zhongjin-online'] = 0
cur_count['canfu'] = 0
cur_count['lichu-test'] = 0
cur_count['fendu'] = 0

def _monitor(db, channel, text = '', bot = None):
    """
    监控某一渠道下的数据
    :param db: 
    :param channel: 
    :return: 
    """
    rows = _get_channel(db, channel)
    cur = _get_channel_distinct(db, channel)
    if cur != cur_count[channel]:
        cur_count[channel] = cur
        content = '微信运维\r\n%s\r\n当前已收到的问卷总数: %d， \r\n来自 %d 人' % (text, rows.count(), cur)
        try:
            users = ['WECHAT', '魏峰']
            for user in users:
                bot.send_msg(content, user)
        except Exception as e:
            log.error(e)


def monitor():
    """
    通过微信健康问卷数据
    :return: 
    """
    while True:
        _monitor(db, channel='lichu-test', text='利楚，问卷统计', bot=bot)
        _monitor(db, channel='canfu', text='灿福，问卷统计', bot=bot)
        _monitor(db2, channel='zhongjin-online', text='中金公司，问卷统计', bot=bot)
        _monitor(db, channel='fendu', text='分度，问卷统计', bot=bot)
        time.sleep(3600)






if __name__ == '__main__':
    db, client = _get_db_client()
    db2, client2 = _get_db_client(host= '120.132.101.30', port = 27137)
    bot = WeBot()
    bot.start_bot()
    threading.Thread(target=monitor).start()
    log.info('监控运行中。。。。。。。。。')

